package com.ligongmusic.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ligongmusic.R;
import com.ligongmusic.adapter.UniversalAdapter;
import com.ligongmusic.adapter.ViewHolder;
import com.ligongmusic.domain.CommentsBean;
import com.ligongmusic.domain.DynamicDomain;
import com.ligongmusic.domain.Upload;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.NetWorkUtils.NetWorkCallBack;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.TopManager;
import com.ligongmusic.view.XListView;
import com.ligongmusic.view.XListView.IXListViewListener;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("deprecation")
public class CommentList extends Activity implements IXListViewListener {
    private Upload musicInfo;
    private XListView mListView;
    private int page = 0, size = 10;
    private List<CommentsBean> commentsList;
    private UniversalAdapter<CommentsBean> adapter;
    private boolean hasData = true;
    private Handler mHandler = new Handler();
    private boolean click = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comments);
        musicInfo = (Upload) getIntent().getSerializableExtra("comments");
        initView();
    }

    private void initView() {
        TopManager.getTopManager(this).showTop(true, "评论列表", new OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(0x6);
                finish();
            }
        });
        mListView = (XListView) findViewById(R.id.comments_list);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(this);
        ImageView head = (ImageView) findViewById(R.id.user_head);
        ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + GlobalParams.userImageUrl, head);
        SpannableStringBuilder builder = new SpannableStringBuilder(GlobalParams.nickName + "分享了单曲");
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(30);
        ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.color_red));
        builder.setSpan(span, 0, GlobalParams.nickName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(sizeSpan, 0, GlobalParams.nickName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ((TextView) findViewById(R.id.tv_share_info)).setText(builder);
        ((TextView) findViewById(R.id.tv_upload_date)).setText(/*musicInfo.getUpload_date() == null ? "" :*/ StringUtils.getYear(musicInfo.getUploaddate()));
        ImageView musicIcon = (ImageView) findViewById(R.id.music_icon);
        ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + musicInfo.getCover(), musicIcon);
        ((TextView) findViewById(R.id.tv_music_name)).setText(musicInfo.getSongname());
        ((TextView) findViewById(R.id.tv_singer)).setText(GlobalParams.nickName + "");
        ((Button) findViewById(R.id.send_comments)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!click)
                    return;
                String comment = ((EditText) findViewById(R.id.et_comments)).getText().toString().trim();
                if (StringUtils.isEmpty(comment)) {
                    Toast.makeText(getApplicationContext(), "评论内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                writeComments(musicInfo.getId(), comment);
            }
        });
        getCommentsList();
    }

    private void getCommentsList() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        pairs.add(new BasicNameValuePair("page", page + ""));
        pairs.add(new BasicNameValuePair("size", size + ""));
        pairs.add(new BasicNameValuePair("songid", musicInfo.getId() + ""));
        NetWorkUtils.getRequest(pairs, GlobalParams.COMMENTS_LIST, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                onLoad();
                LoggerUtils.getLog(CommentList.class).error(result);
                if (commentsList == null)
                    commentsList = new ArrayList<CommentsBean>();
                if (page == 0)// 如果是第一页，重置数据集合
                    commentsList.clear();
                List<CommentsBean> temp = JsonUtils.jsonToBeanList(result, CommentsBean.class);
                if (temp == null)
                    return;
                for (int i = 0; i < temp.size(); i++)
                    commentsList.add(temp.get(i));
                mListView.setPullLoadEnable(temp.size() == size);//当还有数据的时候设置可以下拉
                hasData = temp.size() == size;
                setAdapter();
            }

            @Override
            public void error(String message) {
                LoggerUtils.getLog(CommentList.class).error(message);
            }

            @Override
            public void error() {
                // TODO Auto-generated method stub
            }
        });
    }

    private void setAdapter() {
        if (adapter == null) {
            adapter = new UniversalAdapter<CommentsBean>(CommentList.this, commentsList, R.layout.comments_item) {
                @Override
                public void convert(ViewHolder holder, CommentsBean t, int position) {
                    ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getPhoto(), (ImageView) holder.getView(R.id.user_head));
                    holder.setText(R.id.tv_user_name, t.getComment_name());
//					LoggerUtils.getLog(CommentsActivity.class).error(t.toString());
//					LoggerUtils.getLog(CommentsActivity.class).error(t.getComment_name());

                    holder.setText(R.id.tv_comments_time, t.getDate() == 0 ? "未知时间" : StringUtils.ms2Date(t.getDate()));
                    holder.setText(R.id.tv_comments_content, t.getContent());
                }
            };
            mListView.setAdapter(adapter);
        } else
            adapter.refresh(commentsList);
    }

    private void writeComments(int sid, String commentContent) {
        click = false;
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        pairs.add(new BasicNameValuePair("songid", sid + ""));
        pairs.add(new BasicNameValuePair("content", URLEncoder.encode(commentContent)));
        pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
        NetWorkUtils.getRequest(pairs, GlobalParams.WRITE_COMMENTS, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                click = true;
                LoggerUtils.getLog(CommentList.class).error(result);
                if ("200".equals(JsonUtils.getString(result, "code"))) {
                    ((EditText) findViewById(R.id.et_comments)).setText("");
                    // 刷新界面，并将page设置为0
                    page = 0;
                    getCommentsList();
                }
            }

            @Override
            public void error(String message) {
                click = true;
                LoggerUtils.getLog(CommentList.class).error(message);
            }

            @Override
            public void error() {
                // TODO Auto-generated method stub
                click = true;
            }
        });
    }


    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(StringUtils.getTime(System.currentTimeMillis()));
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hasData = true;
                page = 0;
                getCommentsList();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (hasData) {
                    page++;
                    getCommentsList();
                } else {
                    onLoad();
                }
            }
        }, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x6) {
            setResult(0x6);
            finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
